import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/components/bottom_navigation_bar_widget.dart';
import 'package:wanandroid_flutter/config/default.config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:event_bus/event_bus.dart';

import 'package:wanandroid_flutter/common/application.dart';
import 'package:wanandroid_flutter/event/theme_change_event.dart';

void main() async {
  bool themeIndex = await getTheme();
  runApp(MyApp(themeIndex));
}

class MyApp extends StatefulWidget {
  final bool themeIndex;
  MyApp(this.themeIndex);

  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  ThemeData themeData;

  void initState() {
    super.initState();
    Application.eventBus = EventBus();
    themeData = GlobalConfig.getThemeData(widget.themeIndex);
    this.registerThemeEvent();
  }

  @override
  void dispose() {
    Application.eventBus.destroy();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'WanAndroid App',
      debugShowCheckedModeBanner: true,
      home: BottomNavigationBarWidget(),
      theme: themeData,
    );
  }

  /// =======================================
  void registerThemeEvent() {
    Application.eventBus
        .on<ThemeChangeEvent>()
        .listen((ThemeChangeEvent onData) => this.changeTheme(onData));
  }

  void changeTheme(ThemeChangeEvent onData) {
    setState(() {
      themeData = GlobalConfig.getThemeData(onData.dark);
    });
  }
}

Future<bool> getTheme() async {
  SharedPreferences sp = await SharedPreferences.getInstance();
  bool themeIndex = sp.getBool('themeIndex');
  if (themeIndex == null) {
    themeIndex = false;
  }
  return themeIndex;
}

// void main() => runApp(MyApp());

// class MyApp extends StatelessWidget {
//   @override
//   Widget build(BuildContext context) {
//     return MaterialApp(
//       title: 'WanAndroid App',
//       debugShowCheckedModeBanner: true,
//       home: BottomNavigationBarWidget(),
//       theme: ThemeData(
//         primarySwatch: Colors.deepOrange,
//       ),
//     );
//   }
// }
